package com.lsl.observer_pattern.example2.generic;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * description:
 *
 * @author: liushengli
 * data: 2023/1/13
 */
public abstract class Observable<S extends Observable, O extends Observer,A> {

    protected final List<O> observers;

    public Observable() {
        this.observers = new CopyOnWriteArrayList<>();
    }

    public void addObserver(O observer) {
        this.observers.add(observer);
    }

    public void removeObserver(O observer) {
        this.observers.remove(observer);
    }

    /**
     * Notify observers.
     */
    @SuppressWarnings("unchecked")
    public void notifyObservers(A argument) {
        for (var observer : observers) {
            observer.update((S) this, argument);
        }
    }
}